package com.lagou.filter;

import com.lagou.util.IpFlushFirewall;
import com.lagou.util.HttpResponseStatusUtil;
import com.lagou.util.IpFlushFirewall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * <p>Title: IP防爆刷过滤器</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: http://www.ubisys.com.cn/</p>
 *
 * @Auther: cw
 * @Date: 2020/7/22 20:57
 */
@Component
public class IpRequestFilter extends HttpResponseStatusUtil implements GlobalFilter, Ordered {

    @Value("${config.request.iplimit.apis}")
    private String[] apis;

    @Value("${config.response.message.seeother}")
    private String seeOtherStatusText;

    @Autowired
    private IpFlushFirewall ipFlushFirewall;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String restrictApi : apis) {
            if (path.toLowerCase().startsWith(restrictApi)) {
                return doFilter(exchange, chain);
            }
        }
        return chain.filter(exchange);
    }

    private Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String clientIp = ipFlushFirewall.getRequestClientIP(exchange.getRequest());

        boolean ipLimited = ipFlushFirewall.isIpLimited(clientIp);
        if (ipLimited) {
            return responseStatusAndMessage(exchange.getResponse(), HttpStatus.SEE_OTHER, seeOtherStatusText);
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
